package com.linq.cool.sdk.template;

import com.alibaba.fastjson.JSON;

import com.linq.cool.qqbot.myqq.utils.json.JsonUtils;
import com.linq.cool.sdk.config.TuringRobotProperties;
import com.linq.cool.sdk.dto.TuringReceiveQQMsgDto;
import com.linq.cool.sdk.request.turing.InputText;
import com.linq.cool.sdk.request.turing.Perception;
import com.linq.cool.sdk.request.turing.TuringRobotRequest;
import com.linq.cool.sdk.request.turing.UserInfo;
import com.linq.cool.sdk.response.turing.TuringRobotResponse;
import com.mzlion.easyokhttp.HttpClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author: yqlin
 * @date: 2021/7/4 20:38
 * @description:
 */
@SuppressWarnings("unchecked")
@Slf4j
@Component
@RequiredArgsConstructor
public class TuringHttpRequestTemplate {
    private final TuringRobotProperties turingRobotProperties;

    public TuringRobotResponse doRequest(TuringReceiveQQMsgDto dto) {
        final String url = turingRobotProperties.getBaseUri();
        TuringRobotRequest turingRequest = new TuringRobotRequest()
                .setPerception(new Perception().setInputText(new InputText().setText(dto.getMsg())))
                .setUserInfo(new UserInfo().setUserId(dto.getQq()).setApiKey(turingRobotProperties.getApiKey()));
        log.info("发送请求 POST: {} ,请求体: {}", url, JSON.toJSONString(turingRequest));
        String turingResponse = HttpClient.textBody(url)
                .json(turingRequest)
                .charset("utf8")
                .asString();
        log.info("返回数据:\n {}", JsonUtils.printJson(turingResponse));
        return JSON.parseObject(turingResponse, TuringRobotResponse.class);
    }

    public String getReplyMessage(TuringReceiveQQMsgDto dto) {
        TuringRobotResponse turingRobotResponse = doRequest(dto);
        List<Map<String, Object>> results = turingRobotResponse.getResults();
        for (Map<String, Object> result : results) {
            Map values = JSON.parseObject(result.get("values").toString(), Map.class);
            Object text = values.get("text");
            if (null != text) {
                return String.valueOf(text);
            }
        }
        return null;
    }

}
